<template>
  <div>
    <el-tag
      v-for="tag in c_dynamicTags"
      :key="tag"
      closable
      type="info"
      :disable-transitions="false"
      @close="handleClose(tag)"
    >
      {{ tag }}
    </el-tag>
    <el-input
      v-if="inputVisible"
      ref="saveTagInput"
      v-model="inputValue"
      class="input-new-tag"
      size="small"
      @keyup.enter.native="handleInputConfirm"
      @blur="handleInputConfirm"
    />
    <i v-else class="el-icon-plus button-new-tag" @click="showInput" />
  </div>
</template>

<script>
export default {
  model: {
    prop: 'value',
    event: 'change'
  },
  props: {
    value: {
      type: Array,
      default: () => {
        return []
      }
    }
  },
  data() {
    return {
      dynamicTags: [],
      inputVisible: false,
      inputValue: ''
    }
  },
  computed: {
    c_dynamicTags: {
      get() {
        return this.value
      },
      set(v) {
        this.dynamicTags = v
      }
    }
  },
  methods: {
    emit() {
      this.$emit('change', this.c_dynamicTags)
    },
    handleClose(tag) {
      this.c_dynamicTags.splice(this.c_dynamicTags.indexOf(tag), 1)
    },

    showInput() {
      this.inputVisible = true
      this.$nextTick(_ => {
        this.$refs.saveTagInput.$refs.input.focus()
      })
    },

    handleInputConfirm() {
      const inputValue = this.inputValue
      if (inputValue) {
        this.c_dynamicTags.push(inputValue)
      }
      this.inputVisible = false
      this.inputValue = ''
      this.emit()
    }
  }
}
</script>

<style lang="scss" scoped>
  .el-tag + .el-tag {
    margin-left: 10px;
  }
  .button-new-tag {
    height: 16px;
    width: 16px;
    line-height: 14px;
    padding-top: 0;
    padding-bottom: 0;
    border-radius: 50%;
    cursor: pointer;
  }
  .button-new-tag:hover{
    color: #FFF;
    background-color: #909399;
  }
  .input-new-tag {
    width: 90px;
    margin-left: 10px;
    vertical-align: bottom;
  }
</style>
